﻿using log4net;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common
{
    public class CacheFileHelper
    {
        const string FileCachePathe = "PrintCacheFile";
        static string BasePath = AppDomain.CurrentDomain.BaseDirectory;
        static string FullPath = BasePath + FileCachePathe;
        static readonly ILog _logger = LogManager.GetLogger(typeof(CacheFileHelper));
        const string ErrorTips_HardDrive = "硬盘已无空间用于缓存文件";
        const string ErrorTips_HardDrive2 = "硬盘已无空间用于缓存文件-且已经删除所有文件夹";
        public static void CacheFile(string FilePath)
        {
            try
            {
                //硬盘空间检查
                if (CheckHardDrive())
                {
                    //文件夹数量检查
                    CheckFolderCount();
                    //复制文件
                    CopyFile(FilePath);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
            }
        }
        /// <summary>
        /// 复制文件到缓存文件夹
        /// </summary>
        /// <param name="FilePath"></param>
        static void CopyFile(string FilePath)
        {
            try
            {
                var CurDT = DateTime.Now;
                var CurDayFolder = $"{FullPath}\\{CurDT.Year}_{CurDT.ToString("MM")}_{CurDT.Day.ToString("D2")}";
                var CurFileName = $"{CurDT.Hour}_{CurDT.Minute}_{CurDT.Second}_{CurDT.Millisecond}";
                var CurFullName = $"{CurDayFolder}\\{CurFileName}{FilePath.Substring(FilePath.LastIndexOf("."))}";
                CheckFolderExist(CurDayFolder);
                if (File.Exists(FilePath))
                {
                    File.Copy(FilePath, CurFullName);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
            }
        }
        /// <summary>
        /// 文件夹数量检查(缓存天数) 不能大于配置项中的个数
        /// </summary>
        /// <returns></returns>
        static void CheckFolderCount()
        {
            try
            {
                //检查缓存父文件夹是否创建
                if (!CheckFolderExist(FullPath))
                {
                    _logger.Error(ErrorTips_HardDrive);
                    return;
                }
                //获取满足条件的文件夹数量
                var FolderList = GetAllFolder(FullPath);
                var DeleteDayCount = FolderList.Count - 30; // PrintConfig.CacheDay;//文件缓存天数
                //删除多余的文件夹
                for (int i = 0; i < DeleteDayCount; i++)
                {
                    Directory.Delete(FolderList[i].FullPath, true);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
            }
        }
        /// <summary>
        /// 硬盘空间检查
        /// </summary>
        /// <returns></returns>
        static bool CheckHardDrive()
        {
            try
            {
                //检查硬盘空间
                if (!CheckHardDriveFreeSpace())
                {
                    //检查缓存父文件夹是否创建
                    if (!CheckFolderExist(FullPath))
                    {
                        _logger.Error(ErrorTips_HardDrive);
                        return false;
                    }
                    #region 按天删除文件夹
                    foreach (var item in GetAllFolder(FullPath))
                    {
                        Directory.Delete(item.FullPath, true);
                        if (CheckHardDriveFreeSpace())
                        {
                            //删的满足硬盘空间大小就不删了
                            break;
                        }
                    }
                    //再次检查是否满足硬盘空间大小
                    if (!CheckHardDriveFreeSpace())
                    {
                        _logger.Error(ErrorTips_HardDrive2);
                        return false;
                    }
                    #endregion

                }
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// 获取所有子文件夹
        /// </summary>
        /// <param name="BasePath"></param>
        /// <returns></returns>
        static List<FolderModel> GetAllFolder(string BasePath)
        {
            List<FolderModel> FolderList = new List<FolderModel>();
            try
            {
                string[] subdirectories = Directory.GetDirectories(BasePath);

                foreach (string subdirectory in subdirectories)
                {
                    string subdirectoryName = System.IO.Path.GetFileName(subdirectory);
                    if (subdirectoryName.Count(p => p == '_') == 2)
                    {
                        var TempArray = subdirectoryName.Split('_');
                        if (TempArray.Length == 3)
                        {
                            var TempDateTime = GetDate(TempArray[0], TempArray[1], TempArray[2]);
                            if (TempDateTime != null)
                            {
                                FolderList.Add(new FolderModel() { dateTime = TempDateTime.Value, FullPath = subdirectory });
                            }
                        }
                    }
                }
                return FolderList.OrderBy(p => p.dateTime).ToList();
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
                return FolderList;
            }
        }
        /// <summary>
        /// 字符串转日期
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        public static DateTime? GetDate(string year, string month, string day)
        {
            try
            {
                string dateString = $"{year}-{month}-{day}";
                DateTime date = DateTime.ParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                return date;
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
                return null;
            }
        }
        /// <summary>
        /// 检查文件夹是否存在，不存在创建。
        /// </summary>
        /// <param name="Path"></param>
        static bool CheckFolderExist(string Path)
        {
            try
            {
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// 检查硬盘可用空间
        /// </summary>
        /// <returns></returns>
        static bool CheckHardDriveFreeSpace()
        {
            try
            {
                // 获取程序所在的硬盘
                DriveInfo drive = new DriveInfo(System.IO.Path.GetPathRoot(BasePath));

                // 获取硬盘的可用空间大小
                long availableSpace = drive.AvailableFreeSpace;
                //MB
                long availableSpaceInMB = availableSpace / (1024 * 1024);
                // 打印可用空间大小
                System.Diagnostics.Debug.WriteLine("Available free space: {0} MB", availableSpaceInMB);
                if (availableSpaceInMB > 500) //HardDiskFreeSpace 硬盘可用空间 单位MB
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} 异常！错误原因{ex.Message}");
                return false;
            }
        }


        /// <summary>
        /// 文件夹模型
        /// </summary>
        private class FolderModel
        {
            /// <summary>
            /// 转换为日期格式
            /// </summary>
            public DateTime dateTime { get; set; }
            /// <summary>
            /// 完整路径
            /// </summary>
            public string FullPath { get; set; }
        }
    }
}
